import React, { FunctionComponent, useRef, useState } from 'react';
import { Divider, Image, Layout, message, Typography } from 'antd';
import MaterialGroupTree, { MaterialGroupTreeAction } from './MaterialGroupTree';
import * as API from '@/services';
import { useUpdateEffect } from 'ahooks';

import MoveQuickForm from './MoveQuickForm';
import defaultPlaceholderPng from '@/assets/placeholder.png';
import { EditOutlined } from '@ant-design/icons';
import ModifyNameQuickForm from './ModifyNameQuickForm';
import { KfModal, KfPagingTableComp, KfPagingTablePagePropsAction, platformGetTcVideoInfo, useBackendEnum } from 'kf-web-library';
import QuickMaterialForm from './QuickForm';
import { defaultGetTcVideoInfo } from '@kf-web-library/utils/src/upload';
import { MaterialType } from '@/components';

interface MaterialListProps {
  type: MaterialType;
}

type Entity = API.Material;
type EntityPageQueryParams = API.MaterialPageQueryParams;
const EntityQuickForm = QuickMaterialForm;

const MaterialList: FunctionComponent<MaterialListProps> = (props) => {
  const { type } = props;
  const tableActionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const treeActionRef = useRef<MaterialGroupTreeAction>();
  const [groupId, setGroupId] = useState<number | string | undefined>(undefined);

  const { enumDict } = useBackendEnum();
  const typeName = enumDict['MaterialType'][type].enumDesc;

  useUpdateEffect(() => {
    tableActionRef.current?.reload();
    return () => {
      // do something
    };
  }, [groupId]);

  return (
    <Layout className={'material-group-page-layout'}>
      <Layout.Sider theme={'light'} collapsible={false} width={280} className={'material-group-tree-sider'}>
        <MaterialGroupTree
          actionRef={treeActionRef}
          selectedKey={groupId}
          type={type}
          onSelect={(selectedKeys) => {
            setGroupId(selectedKeys);
          }}
        />
      </Layout.Sider>
      <Layout.Content>
        <KfPagingTableComp<Entity, EntityPageQueryParams>
          actionRef={tableActionRef}
          entityTypeName={typeName}
          headerTitle={null}
          wrapper={({ children: dom }) => <>{dom}</>}
          //hasPageHeader={false}
          proTable={{
            columnsState: {
              persistenceKey: `${typeName}素材`,
            },
            search: {
              filterType: 'query',
            },
            tableAlertBatchActions: (abaProps) => {
              return [<a onClick={() => tableActionRef.current?.openFloating.multi?.moveModal(abaProps.selectedRows)}>批量移动</a>];
            },
          }}
          pagingQuery={(params) => API.queryMaterials({ ...params, groupId, types: [type] })}
          onFloatingSubmit={(fltTypeName) => {
            if (['createModal', 'moveModal'].includes(fltTypeName)) {
              treeActionRef.current?.reload();
            }
          }}
          opActionsDef={{
            single: {
              deleteOne: (record) => {
                KfModal.deleteConfirm(record.name as string, () => {
                  API.deleteMaterial(record.id!).then((res) => {
                    if (res.flag) {
                      message.info('删除成功');
                      tableActionRef.current?.reload();
                      treeActionRef.current?.reload();
                      if (tableActionRef.current?.proTableAction?.clearSelected) {
                        tableActionRef.current?.proTableAction?.clearSelected();
                      }
                    }
                  });
                });
              },
            },
            multi: {
              deleteMultiple: (records) => {
                KfModal.batchDeleteConfirm(records.length, () => {
                  API.deleteMaterials(records.map((r) => r.id!)).then((res) => {
                    if (res.flag) {
                      message.info('批量删除成功');
                      tableActionRef.current?.reload();
                      treeActionRef.current?.reload();
                    }
                  });
                });
              },
            },
          }}
          opFloatingsDef={{
            noargs: {
              createModal: {
                show: true,
                buttonText: `上传${typeName}`,
                fltRender: () => ({
                  title: `上传${typeName}`,
                  content: <QuickMaterialForm formType={'create'} type={type} defaultGroupId={groupId} />,
                }),
              },
            },
            single: {
              moveModal: (record) => ({
                title: `移动分组`,
                width: 600,
                content: <MoveQuickForm formType={'move'} ids={[record.id]} type={type} />,
              }),
              modifyNameModal: (record) => ({
                title: `重命名`,
                width: 400,
                content: <ModifyNameQuickForm formType={'modify'} bizId={record.id} />,
              }),
            },
            multi: {
              moveModal: (entitys) => ({
                title: `移动分组`,
                width: 600,
                content: <MoveQuickForm formType={'move'} ids={entitys.map((record) => record.id)} type={type} />,
              }),
            },
          }}
          columns={[
            {
              title: ``,
              width: 60,
              dataIndex: nameof<Entity>((x) => x.url),
              sorter: false,
              hideInSearch: true,
              hideInTable: type === 'FILE',
              ellipsis: true,
              render: (_, record) => {
                if (type === 'IMG') {
                  return <Image width={32} src={record.url} fallback={defaultPlaceholderPng} />;
                } else if (type === 'VIDEO') {
                  const tcVideoInfo = defaultGetTcVideoInfo(record.url!);
                  return (
                    <a rel={'noreferrer'} href={tcVideoInfo.tcVideo} target={'_blank'}>
                      <img
                        src={tcVideoInfo.screenshot}
                        style={{ width: 32 }}
                        onError={({ currentTarget }) => {
                          currentTarget.onerror = null; // prevents looping
                          currentTarget.src = defaultPlaceholderPng;
                        }}
                      />
                    </a>
                  );
                } else {
                  return null;
                }
              },
            },
            {
              title: `${typeName}名称`,
              dataIndex: nameof<Entity>((x) => x.name),
              sorter: false,
              hideInSearch: false,
              ellipsis: false,
              render: (_, record) => {
                return (
                  <div>
                    <span>{record.name}</span>
                    <span style={{ marginLeft: 18 }}>
                      <a onClick={() => tableActionRef.current?.openFloating.single?.modifyNameModal(record)}>
                        <EditOutlined />
                      </a>
                    </span>
                  </div>
                );
              },
            },

            {
              title: '上传时间',
              width: 150,
              dataIndex: nameof<Entity>((x) => x.createTime),
              sorter: false,
              hideInSearch: true,
              ellipsis: true,
            },
            {
              title: '操作',
              fixed: 'right',
              width: 130,
              dataIndex: 'option',
              valueType: 'option',
              render: (_, record) => (
                <>
                  <a onClick={() => tableActionRef.current?.openFloating.single?.moveModal(record)}>移动</a>
                  <Divider type="vertical" />
                  <a onClick={() => tableActionRef.current?.executeAction.single?.deleteOne(record)}>
                    <Typography.Text type="danger">删除</Typography.Text>
                  </a>
                </>
              ),
            },
          ]}
        />
      </Layout.Content>
    </Layout>
  );
};

export default MaterialList;
